import Common from './common';
import {
    toast,
    promptBox
} from 'nc-lightapp-front';

import TurnCardAction from './form';

let executeBillData = []

export default class RowHandle extends Common{
    constructor(comp) {
        super();
        this.comp = comp;
    }

    extend=[TurnCardAction]

    //指派弹窗确定事件
    getResult =  async(value) =>{
        const {props, action} = this.comp
        const {emp,form} = props
        let selectedRows = []
        if(emp.page !== 'main'){
            selectedRows = [{
                ...form.getAllFormValue('card').rows[0]
            }];
        }
        await this.submitOnes(selectedRows,value) 
        action.formAct.toBrowsePage(selectedRows);
    }

    //指派弹窗取消事件
    turnOff =()=>{
        const {props} = this.comp
        const {dispatch} = props
        dispatch({
            type: 'emp/update',
            payload: {
                compositedata: null,
                compositedisplay: false,
            }
        })
    }

    // 获取选中的数据
    getSelectedRows = (selectedRows) => {
        const {props} = this.comp;
        const {emp, editTable, dispatch} = props;

        if(!selectedRows) {
            selectedRows = [];
        }

        if(selectedRows.length <= 0) {
            if(emp.tableSelectAll) {
                selectedRows = editTable.getAllRows('list');
            }
            else {
                selectedRows = editTable.getCheckedRows('list').map((item) => {
                    return item.data;
                });
            }
        }

        if(selectedRows.length <= 0) {
            toast({
                color: 'warning',
                content: emp.language['gx6008-000016'] // 请先勾选待操作的数据!
            });
            return false
        }
        return selectedRows
    }

     // 提交某个单据
     submitOnes = async (selectedRows = [],compositepostdata = null) => {
        const {props} = this.comp;
        const {emp, editTable, dispatch} = props;

        selectedRows = this.getSelectedRows(selectedRows);
        if(selectedRows) {
            let postData = {
                billids: [],
                pk_org: emp.orgValue.refpk
            };

            postData.billids = selectedRows.map((item) => {
                return item.values['pk_partmng'].value
            });

            if(compositepostdata && compositepostdata.content){
                postData = Object.assign({},postData,{content: compositepostdata})
           }
              

            try {
                let res = await dispatch({
                    type: 'emp/submitBill',
                    payload: {
                        postData: postData
                    }
                });
                if(res.success) {
                    if(res.data.content){
                        dispatch({
                            type: 'emp/update',
                            payload:{
                                compositedata: res.data.content,
                                compositedisplay: true
                            }
                        })
                        return ;
                    }else{
                        dispatch({
                            type: 'emp/update',
                            payload:{
                                compositedata: null,
                                compositedisplay: false,
                                compositepostdata: null
                            }
                        })
                        if(this.checkErrorMsg(res)){
                            this.toast({
                                color: 'success',
                                content: emp.language['gx6008-000047'] // 提交成功
                            });
                        }
                    }   
                }
            }
            catch(e) {
                console.error(e);
            }
            this.pubSub.publish('getMainTableData');
        }
    }

    // 收回
    callbackOnes = async (selectedRows) => {
        const {props, action} = this.comp;
        const {dispatch, emp} = props;

        selectedRows = this.getSelectedRows(selectedRows);

        if(selectedRows) {
            let postData = {
                billids: [],
                pk_org: emp.orgValue.refpk
            };

            postData.billids = selectedRows.map((item) => {
                return item.values['pk_partmng'].value;
            });

            try {
                let res = await dispatch({
                    type: 'emp/callbackBill',
                    payload: {
                        postData: postData
                    }
                });

                if(res.success && this.checkErrorMsg(res)) {
                    toast({
                        color: 'success',
                        content: emp.language['gx6008-000048'] // 收回成功
                    });
                }
            }
            catch(e) {
            }
            this.pubSub.publish('getMainTableData');
        }
    }
    
    // 修改
    editOnes = (selectedRows) => {
        const {action} = this.comp;

        selectedRows = this.getSelectedRows(selectedRows);

        if(selectedRows) {
            this.toEditPage(selectedRows);
        }
    }

    // 删除主表格行
    deleteRows = async (selectRows) => {
        const {props, action} = this.comp;
        const {emp, editTable, dispatch} = props;
        let result = true;

        selectRows = action.rowAct.getSelectedRows(selectRows);
        if(selectRows){
            let next = await new Promise((resolve, reject) => {
                promptBox({
                    color: "warning",
                    title: emp.language['gx6008-000018'],/* 国际化处理： 提示*/
                    content: emp.language['gx6008-000019'],/* 国际化处理： 确定要删除所选数据吗？*/
                    beSureBtnClick: async () => {
                        resolve(true);
                    }
                });
            });
            if(!next) {
                return;
            }
            let postData = {
                billids: [],
                pk_org: emp.orgValue.refpk
            };
            selectRows.map((item) => {
                postData.billids.push(item.values.pk_partmng['value']);
            });

            try {
                let res = await dispatch({
                    type: 'emp/deleteTableRows',
                    payload: {
                        postData: postData
                    }
                });

                if(res.success && this.checkErrorMsg(res)) {
                    toast({
                        color: 'success',
                        content: emp.language['gx6008-000017'] // 删除成功
                    });
                    this.pubSub.publish('getMainTableData');
                    result = true;
                }
            }
            catch(e) {
                result = false;
            }

            return result;
        }
    }

    // 复制一个单据
    copyOnes = async (selectRows) => {
        const {props, action} = this.comp;
        const {emp, editTable, dispatch} = props;

        selectRows = action.rowAct.getSelectedRows(selectRows);
        if(selectRows) {
            let postData = {
                billid: selectRows[0].values['pk_partmng'].value,
                pk_org: emp.orgValue.refpk
            };
            try {
                let res = await dispatch({
                    type: 'emp/copyOneBill',
                    payload: {
                        postData: postData
                    }
                });

                if(res.success && this.checkErrorMsg(res)) {
                    this.toEditPage(selectRows, res.data.formData.card, {
                        isBillCodeEditable: res.data.isBillCodeEditable
                    });
                }
            }
            catch(e) {
                console.error(e);
            }
        }
    }

    // 检查返回值里是否有 errorMsg
    checkErrorMsg = (res) => {
        if(res && res.data && (res.data.errorMsg || res.data.message)) {
            this.toast({
                color: 'danger',
                content: res.data.errorMsg || res.data.message
            });
            return false
        }

        return true;
    }

    // 查看审批详情
    previewApproveInfo = (selectedRows) => {
        const {props, action} = this.comp;
        const {emp, editTable, dispatch} = props;

        const rowData = selectedRows[0].values;
        let billType = rowData['transtype'].value || rowData['pk_billtype'].value || '6101';
        let billId = selectedRows[0].values['pk_partmng'].value;

        dispatch({
            type: 'emp/update',
            payload: {
                approveModalVisible: true,
                approveBillType: billType,
                approveBillId: billId
            }
        });
    }

    // 打开执行弹窗
    openExecModal = async (selectedRows) => {
        const {props} = this.comp;
        const {emp, dispatch} = props;

        let selectRows = this.getSelectedRows(selectedRows);
        executeBillData = this.deepCopy(selectRows);

        let billids = selectRows.map((item) => {
            return item.values.pk_partmng['value'];
        });

        let checkResult = await dispatch({
            type: 'emp/checkBeforeExecute',
            payload: {
                postData: {
                    pk_org: emp.orgValue.refpk,
                    billids: billids
                }
            }
        });

        if(checkResult.data && selectRows && selectRows.length > 0) {
            this.comp.props.dispatch({
                type: 'emp/update',
                payload: {
                    executeModalVisible: true
                }
            });
        }
    }

    // 关闭执行弹窗
    closeExecuteModal = () => {
        this.comp.props.dispatch({
            type: 'emp/update',
            payload: {
                executeModalVisible: false
            }
        });
        executeBillData = [];
    }

    // 执行单据
    executeBill = async () => {
        const {props, action} = this.comp;
        const {emp, dispatch} = props;
        if(!emp.executeModalApplyDate) {
            this.toast({
                color: 'danger',
                content:emp.language['gx6008-000281']
            });
            return
        }
        let selectRows = this.getSelectedRows(executeBillData);
        let postData = {
            billids: [],
            effectDate: emp.executeModalApplyDate,
            pk_org: emp.orgValue.refpk
        };

        selectRows.map((item) => {
            postData.billids.push(item.values.pk_partmng['value']);
        });

        try {
            let res = await dispatch({
                type: 'emp/executeBill',
                payload: {
                    postData: postData
                }
            });
    
            if(res && res.success) {
                dispatch({
                    type: 'emp/update',
                    payload: {
                        executeModalApplyDate: ''
                    }
                });
                this.pubSub.publish('getMainTableData');
                this.closeExecuteModal();
                if(emp.page === 'add' || emp.page === 'edit') {
                    this.toBrowsePage(selectRows);
                }
            }
        }
        catch(e) {
            this.closeExecuteModal();
        }
    }
}